package services;

import java.util.List;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.openjpa.persistence.PersistenceException;
import domains.User;

public class UserService implements IUserService {
	EntityManagerFactory tmp;

	public UserService (EntityManagerFactory emf) {
		tmp = emf;
	}

	@Override
	public int addUser(String login, String password, String password2, String code, String fio, String birthday) {
	    if ((login.equals(""))||(password.equals(""))||(password2.equals(""))||(code.equals(""))||(fio.equals(""))||(birthday.equals(""))) 
        	 return 1; //пустые поля
		 User user = DAOFactory.getInstance().getUserService().findUserByLogin(login);
		 if (user != null) return 2; //уже есть пользователь с таким логином
         if (!password.equals(password2)) return 3; //не совпадают введенные пароли
         if (!code.equals("123456")) return 4; //не верный код защиты
         
		EntityManager em = tmp.createEntityManager();
		em.getTransaction().begin();
	 try {	
		user = new User();
		user.setFio(fio);
		user.setBirthday(birthday);
		user.setLogin(login);
		user.setPassword(password);
		user.setStatus(false);
		user.setImages(null);
	
		em.persist(user);
	    em.getTransaction().commit();
	 } 	
	 catch (Exception e) {
		e.printStackTrace();
		em.getTransaction().rollback();
	 }	
	 finally {
	    em.close();
	 }	
	 return 0;
}

	@Override
	public User findUserById(Integer id) throws PersistenceException {
			if (id == null) {
				throw new PersistenceException("User id for getting cannot be null!", null, id, false);
			}
			// Creating entity manager to work with entity
			EntityManager entityManager = tmp.createEntityManager();
			// Begin a new local transaction so that we can persist a new entity
			entityManager.getTransaction().begin();
			User user = null;
			try {
				// Finding User by its id
				user = entityManager.find(User.class, id);
				// Commit the transaction, which will cause the entity to
				// be stored in the database
				entityManager.getTransaction().commit();
			} 
			catch (Exception e) {
				// Catching exceptions and rollback of transaction
				entityManager.getTransaction().rollback();
				// throwing exception further
				throw new PersistenceException(null, null, e, false);
			} finally {
				// It is always good practice to close the EntityManager so that
				// resources are conserved.
				entityManager.close();
			}
			return user;
	}

	@Override
	public User findUserByLogin(String login) {
		User user = null;
		EntityManager em = tmp.createEntityManager();
		em.getTransaction().begin();
	
		try {
			// Создаем объект запроса
			Query query = em.createQuery("SELECT x FROM User x WHERE x.login = ?1");
			query.setParameter(1, login);
			List<User> list = query.getResultList();
			 if (CollectionUtils.isNotEmpty(list)) 
				user = list.get(0);
			em.getTransaction().commit();
		} 
		catch (Exception e) {
			e.printStackTrace();

			// Откат транзакции в случае ошибки
			em.getTransaction().rollback();
		} 
		finally {

			// Завершение работы с менеджером сущностей
			em.close();
		}
		return user;
	}
	
	@Override
	public boolean findUserByLoginAndPassword(String login, String password) {
		boolean b = false;
		EntityManager em = tmp.createEntityManager();
		em.getTransaction().begin();
	
		try {
			// Создаем объект запроса
			Query query = em.createQuery("SELECT x FROM User x WHERE x.login = ?1 AND x.password = ?2");
			query.setParameter(1, login);
			query.setParameter(2, password);
			List<User> list = query.getResultList();
			 if (CollectionUtils.isNotEmpty(list)) 
				b = true;
			em.getTransaction().commit();
		} 
		catch (Exception e) {
			e.printStackTrace();

			// Откат транзакции в случае ошибки
			em.getTransaction().rollback();
		} 
		finally {

			// Завершение работы с менеджером сущностей
			em.close();
		}
		return b;
	}

	@Override
	public void deleteUserById(Integer id_user) {
		 if (id_user == null) return;
		   
		  // Creating entity manager to work with entity
		  EntityManager entityManager = tmp.createEntityManager();
		  //Begin a new local transaction so that we can persist a new entity
		  entityManager.getTransaction().begin();

		try {
		 // Finding user by its id
		 User user_del = entityManager.find(User.class, id_user);

		 // Removing user
		 entityManager.remove(user_del);
	 
		 // Commit the transaction, which will cause the entity to
		 // be stored in the database
		 entityManager.getTransaction().commit();

		} 
		
		catch (Exception e) {
	  // Catching exceptions and rollback of transaction
		entityManager.getTransaction().rollback();
		// throwing exception further
		throw new PersistenceException(null, null, e, false);
		} 
		
		finally {
		// It is always good practice to close the EntityManager so that
		// resources are conserved.
		entityManager.close();
	    }
		return;
	}

	@Override
	public int updateUser(Integer id_user, String fio, String birthday, String login, String password_old, String password, String password2) {
		User user = DAOFactory.getInstance().getUserService().findUserById(id_user);
		if (user==null) return 1; //пользователя с таким id нету в БД
		if (!password_old.equals(user.getPassword())) return 2; //введен не верный старый пароль
		if (!password.equals(password2)) return 3; //подтвержденный и введенный пароли не совпадают
		
		EntityManager em = tmp.createEntityManager();
		em.getTransaction().begin();
	 try {	
	    User user2 = em.find(User.class, user.getId());
	    if (fio.equals(""))
	        user2.setFio(user.getFio());
	     else 
	        user2.setFio(fio);
	    
	    if (birthday.equals(""))
		    user2.setBirthday(user.getBirthday());
		 else 
		    user2.setBirthday(birthday);
	    
	    if (login.equals(""))
		    user2.setLogin(user.getLogin());
		 else 
		    user2.setLogin(login);
	    
	    if (password.equals(""))
		    user2.setPassword(user.getPassword());
		 else 
		    user2.setPassword(password);
	
		user2.setImages(user.getImages());
		 
	    em.getTransaction().commit();
	 } 	
	 catch (Exception e) {
		e.printStackTrace();
		em.getTransaction().rollback();
	 }	
	 finally {
	    em.close();
	 }	
	 return 0;
	}
}
